/*
  mdpripoj.c
*/
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <syslog.h>

#include "../libmdemonapl/mdemonapl.h"
#include "ping.h"
#include "closepppd.h"
#include "closeopenvpn.h"


int main(int argc, char *argv[]){
 
  int i;
  int len;
  int result;
  int buffer = 256;
  char *received;
  int nread;
  char *tel, *text;
  int tel_len = 0;
  int text_len = 0;
  char *response;
  char *send_sms_command;
  char *pom;
  //char *filenameuser = "/usr/local/etc/mdemon/mdemonusr.conf";
  //char *filenameadress = "/usr/local/etc/mdemon/mdemonadr.conf";
  char *filevpnname = "/usr/local/etc/mdemon/openvpn.pid";
  int ex;
  
  // nacitanie vstupnych parametrov
  openlog("mdemon/pripoj", LOG_PID|LOG_CONS, LOG_USER);
  if (argc != 1)
  {
    perror("zle vstupne data: nespravny pocet argumentov");
    syslog(LOG_ERR, "zle vstupne data: nespravny pocet argumentov - %m");
    return -1;
  }
  
  int fd = mdconnect_and_auth();
  if (fd < 0)
  {
    perror("nepodarilo sa spojit s programom MDemon:");
    syslog(LOG_ERR, "nepodarilo sa spojit s programom MDemon: %m");
    return 1;
  }
  
  if (mdsuspend(fd) != 0)
  {
    syslog(LOG_ERR, "nepodarilo sa odpojit MDemon od mobilu: %m");
    return 1;
  }
 
  int ppd;
  ppd = fork();
  if (ppd < 0)
  {
    perror("ppd-fork:");
    syslog(LOG_INFO, "ppd-fork: %m");
    mdresume(fd);
  }
  else if (ppd == 0)
  {
    openlog("mdemon/pripoj(wvdial)", LOG_PID|LOG_CONS, LOG_USER);
    syslog(LOG_INFO, "spustam wvdial");
    char *const wv_argv[] = {"wvdial", 0}; 
    ex = execv("/usr/bin/wvdial", wv_argv);
    if (ex == -1)
    {
      perror("wvdial:");
      syslog(LOG_ERR, "spustam wvdial");
      mdresume(fd);    
    }
  }
  else
  {   
    sleep(10);
    int vpn = fork();
    if (vpn < 0)
    {
      perror("vpn-fork:");
      syslog(LOG_INFO, "vpn-fork: %m");
      //kill(ppd, SIGKILL);
      printf("volam closeppd:%d\n", closepppd(0));
      mdresume(fd);
    }
    else if (vpn == 0)
    {
      openlog("mdemon/pripoj(vpn)", LOG_PID|LOG_CONS, LOG_USER);
      printf("spustam vpn\n");
      syslog(LOG_INFO, "spustam vpn");
      char *const vpn_argv[] = {"openvpn", "/etc/openvpn/clientptp", 0};
      ex = execv("/usr/sbin/openvpn", vpn_argv);
      if (ex < 0)
      {
	sleep(5);
	unlink(filevpnname);
	perror("openvpn:");
	syslog(LOG_ERR, "openvpn: %m");
      }
      
      
    }
    else{
      FILE *filevpn;
      filevpn = fopen(filevpnname, "w");
      fprintf(filevpn, "%d", vpn);
      fclose(filevpn);
      sleep(10);
      int res = cmd_ping("10.7.2.8");
      if (res == 0)
      {
	printf("pripojenie sa vydarilo\n");
      }
      else
      {
	printf("pripoj-res:%d\n", res);
	syslog(LOG_INFO, "ping: %m");
	printf("volam closeopenvpn:%d\n", closeopenvpn());
	printf("volam closepppd:%d\n", closepppd(0));
	//perror("closepppd:");
	mdresume(fd);
      }
      
    }
    
  }
  return  0; 
 
}

